<?php

class ctrl_pdd_pddOrder extends L {

    /**
     * 描述 ：订单列表页面展示
     * 作者 ：Zoro.Zhu
    **/
    public function index(){
        $this->view->pddOrderState = model_com::getVsConfig('pddOrderState');
        $this->view->_pagingHtml = $this->paging();
        $this->view->headTitle = '订单列表';
        $this->display('/html/pdd/pddOrder.html');
    }

    /**
     * 描述 : 获取分页
     * 作者 : Zoro.Zhu
     */
    public function &paging($params = array()){
        $sql = model_pddOrder::searchSql($params);
        $config = array(
            "<input type=\"checkbox\" name=\"checkAll\">" => '<input type="checkbox" name="check[]" class="checkbox"  value="{`pddOrder`}">',
            '拼多多的订单号<br>阿里采购单号' => array(
                '_attr' => array(
                    'body' => '{`pddOrder`}<br>{`aliOrder`}',
                    'sort' => 'pddOrder'
                )
            ),
            'pdd的销售账号' => array(
                '_attr' => array(
                    'body' => '{`accountPdd`}',
                    'sort' => 'accountPdd'
                )
            ),
            '承诺发货时间<br>成交时间' => array(
                '_attr' => array(
                    'body' => '{`lastShipTime`}<br>{`confirmTime`}',
                    'sort' => 'confirmTime'
                )
            ),
            'PDD售后状态<br>抓单时间' => array(
                '_attr' => array(
                    'body' => '{`pddRefundStatus`}<br>{`addTime`}',
                    'sort' => 'addTime'
                )
            ),
            '成交金额￥<br>买家实际支付金额￥<br>订单状态' => array(
                '_attr' => array(
                    'body' => '{`goodsAmount`}<br>{`payAmount`}<br>{`_orderState`}',
                    'sort' => 'orderState'
                )
            ),
            '产品信息<br>图片 PDDID aliID SKU * 数量' => '{`_skuInfo`}',
            '收件信息' => '{`country`} {`province`} {`city`} {`town`}<br>{`receiverAddress`}<br>{`receiverName`} {`receiverPhone`}',
            '采购总金额<br>采购运费<br>产品采购金额' => '{`purPriceTotal`}<br>{`purShippingFee`}<br>{`purProductFee`}',
            '物流公司<br>物流公司编码<br>快递单号' => '{`logisticsCompanyName`}<br>{`logisticsCompanyNo`}<br>{`logisticsBillNo`}',
            '_attr' => array(
                "attr" => array (
                    "table" => 'id=pddOrderList class="table table-hover table-condensed table-striped table-scroll jsHoverDetails textC"',
                    "btr" => "align='center' class='of-paging_item_odd tr_{`pddOrder`}'",
                ),
                'data' => &$sql,
                'params' => &$params,
                'call' => array($this, 'asCall'),
                'method' => __METHOD__,
                'save' => 'auto',
                'empty' => '查无此数据'
            )
        );
        return $this->_com->paging($config);
    }

    /**
     * 描述 : 整理数据
     * 作者 : Zoro.Zhu
     */
    public function asCall(&$data){
        $pddOrderState = model_com::getVsConfig('pddOrderState');
        $refundStatus = model_com::getVsConfig('refundStatus');
        foreach($data['data'] as &$val){
            $val['_orderState'] = $pddOrderState[$val['orderState']];
            $pddData = json_decode($val['data'], true);
            $val['goodsAmount'] = $pddData['goods_amount'];                       //成交金额
            $val['payAmount'] = $pddData['pay_amount'];                             //买家实际支付金额
            $val['country'] = $pddData['country'];                                  //国
            $val['province'] = $pddData['province'];                                //省
            $val['city'] = $pddData['city'];                                        //市
            $val['town'] = $pddData['town'];                                        //区镇
            $val['receiverAddress'] = $pddData['receiver_address'];                //地址
            $val['receiverName'] = $pddData['receiver_name'];                      //收件人
            $val['receiverPhone'] = $pddData['receiver_phone'];                    //收件人电话
            $val['lastShipTime'] = $pddData['last_ship_time'];                    //承诺发货时间
            $val['pddRefundStatus'] = $refundStatus[$pddData['refund_status']];     //pdd售后状态
            $val['_skuInfo'] = '';
            foreach($pddData['item_list'] as $skuRow){
                $skuInfo = model_pddOrder::skuGetId($skuRow['outer_id']);
                $val['_skuInfo'] .= "<img src='{$skuRow['goods_img']}' style='width: 45px;height: 45px'>{$skuInfo['pddId']} <a target=\"_blank\" href='https://detail.1688.com/offer/{$skuInfo['productId']}.html'>{$skuInfo['productId']}</a> {$skuRow['outer_id']} * {$skuRow['goods_count']}<br>";
            }
            $aliData = json_decode($val['aliData'], true);
            $val['purPriceTotal'] = !empty($aliData['baseInfo']['totalAmount']) ? $aliData['baseInfo']['totalAmount'] : ''; //总采购金额
            $val['purShippingFee'] = !empty($aliData['baseInfo']['shippingFee']) ? $aliData['baseInfo']['shippingFee'] : ''; //采购运费
            $val['purProductFee'] = !empty($aliData['baseInfo']['sumProductPayment']) ? $aliData['baseInfo']['sumProductPayment'] : ''; //产品采购金额
            $val['logisticsCompanyName'] = !empty($aliData['nativeLogistics']['logisticsItems'][0]['logisticsCompanyName']) ? $aliData['nativeLogistics']['logisticsItems'][0]['logisticsCompanyName'] : ''; //物流公司
            $val['logisticsCompanyNo'] = !empty($aliData['nativeLogistics']['logisticsItems'][0]['logisticsCompanyNo']) ? $aliData['nativeLogistics']['logisticsItems'][0]['logisticsCompanyNo'] : ''; //物流公司编码
            $val['logisticsBillNo'] = !empty($aliData['nativeLogistics']['logisticsItems'][0]['logisticsBillNo']) ? $aliData['nativeLogistics']['logisticsItems'][0]['logisticsBillNo'] : ''; //物流单号

        }
    }


    /**
     * 描述 ：按条件导出数据
     * 作者 ：Zoro.Zhu
    **/
    public function exportCsv(){
        $sql = model_pddOrder::searchSql(array('search' => $_GET));
        $data['data'] = L::sql($sql);
        self::asCall($data);
        of_base_com_csv::download('导出数据' . time());                     //导出数据的文件名
        of_base_com_csv::download(array(
            'pdd的订单号',
            'pdd的销售账号',
            '成交时间',
            '抓单时间',
            '承诺发货时间',
            '订单状态',
            '省',
            '市',
            '区镇',
            '地址',
            '收货人姓名',
            '收货人电话',
            '成交金额',
            '买家实际支付金额',
            'ali的订单号',
            '总采购金额',
            '采购运费',
            '产品采购金额',
            '物流公司',
            '物流公司编码',
            '快递单号',
            ));
        foreach ($data['data'] as $row){
            of_base_com_csv::download(array(
                $row['pddOrder'],
                $row['accountPdd'],
                $row['confirmTime'],
                $row['addTime'],
                $row['lastShipTime'],
                $row['orderState'],
                $row['province'],
                $row['city'],
                $row['town'],
                $row['receiverAddress'],
                $row['receiverName'],
                $row['receiverPhone'],
                $row['goodsAmount'],
                $row['payAmount'],
                $row['aliOrder'],
                $row['purPriceTotal'],
                $row['purShippingFee'],
                $row['purProductFee'],
                $row['logisticsCompanyName'],
                $row['logisticsCompanyNo'],
                $row['logisticsBillNo'],
                ));
        }
    }

    /**
     * 描述 ：导出上传运单号模板
     * 作者 ：Zoro.Zhu
     **/
    public function exportTemp(){
        of_base_com_csv::download('上传运单号模板');                     //导出数据的文件名
        of_base_com_csv::download(array('pdd的订单号','pdd的销售账号','快递公司','快递单号',));
    }

    /**
     * 描述 ：审核订单
     * 作者 ：Zoro.Zhu
    **/
    public function checkOrder(){
        if(empty($_POST['pddOrderStr'])){
            return array('state' => 300, 'info' => '单号不能为空');
        }
        if(empty($_POST['orderState'])){
            return array('state' => 301, 'info' => '错误请求');
        }
        $order = explode(',', $_POST['pddOrderStr']);
        $error = '';
        $orderState = model_pddOrder::getOrderState($order);
        foreach ($orderState as $pddOrder => $state){
            if($_POST['orderState'] != 60 && $state != 10){
                $error .= "{$pddOrder}状态不是新订单<br>";
                continue;
            }
            L::sql("UPDATE `pdd_order` 
            SET `orderState` = '{$_POST['orderState']}' 
            WHERE
                `pddOrder` = '{$pddOrder}'");
            if($_POST['orderState'] == 20){
                //加入去阿里巴巴下单的消息队列
                of_base_com_mq::set(['payAliOrder', $pddOrder], ['pddOrder' => $pddOrder]);
            }
        }
        if($error){
            return array('state' => 303, 'info' => $error . '其它订单审核成功！');
        }else{
            return array('state' => 200, 'info' => '审核成功');
        }
    }

    /**
     * 描述 ：上传运单号
     * 作者 ：Zoro.Zhu
    **/
    public function uploadTrackNo(){
        //程序运行不限制时间
        ini_set('max_execution_time', '0');
        //配置内存2G
        ini_set('memory_limit', '2048M');
        $result = array (
            'state' => 0,
            'info' => '文件未上传'
        );
        if (!empty($_POST['file']) && is_array($_POST['file'])) {
            $path = ROOT_DIR . '/data' . $_POST['file'][0];
            $i = 0;
            $row = 0;
            $errorNUM = 0;
            //解析数据
            while ($data = &of_base_com_csv::parse($path)) {
                if($i == 0){
                    $i++;
                    continue;
                }
                $row++;
                if(!empty($data[0]) && !empty($data[1]) && !empty($data[2]) && !empty($data[3])){
                    $orderId = trim($data[0]);
                    $account = trim($data[1]);
                    $logistics = trim($data[2]);
                    $trackNo = trim($data[3]);
                    $token = model_vsAccount::getAccountToken(['account' => $account]);
                    $data['accessToken'] = $token['accessToken'];
                    $data['clientId'] = $token['appKey'];
                    $data['clientSecret'] = $token['appSecret'];
                    $data['order_sn'] = $orderId;
                    $logisticsList = model_pddLogistics::getListName();
                    $data['logistics_id'] = $logisticsList[$logistics];
                    $data['tracking_number'] = $trackNo;
                    $res = model_api_pdd::orderSend($data);
                    //上传运单号成功，修改状态
                    if(!empty($res['is_success'])){
                        L::sql("UPDATE `pdd_order` 
                        SET `orderState` = '55' 
                        WHERE
                            `pddOrder` = '{$orderId}'");
                    }else{
                        $errorNUM++;
                    }
                }else{
                    $errorNUM++;
                }
            }
            $result = array (
                "state" => 1,
                "info" => "总共导入" . ($row) . "条数据, 成功" . ($row - $errorNUM) . "条,失败" . $errorNUM . "条"
            );
        }
        return $result;
    }


}
return true;